package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.准备日期列表数据dateList
        List<LocalDate> dateList = getDateList(begin, end);

        //2.准备营业额列表数据turnoverList
        List<Double> turnoverList = new ArrayList<>();
        //营业额=订单状态已完成的订单总金额
        //查询orders表，条件：状态-已完成，下单时间
        //select sum(amount) from orders where status = 5 and order_time between '2025-10-31 00:00:00' and '2025-10-31 23:59:59.99999'
        dateList.forEach(date -> {
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); //'2025-10-31 00:00:00'
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); //'2025-10-31 23:59:59.99999'
            Double turnover=ordersMapper.sumByMap(map);
            //用来处理营业额为null的情况
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        //3.构造TurnoverReportVO对象并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 统计指定时间范围内每天的新增用户数和总用户数，并封装成UserReportVO对象返回。
     *
     * @param begin 统计开始日期（包含）
     * @param end   统计结束日期（包含）
     * @return 封装了日期列表、每日新增用户数列表和总用户数列表的UserReportVO对象
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.构造dateList数据
        List<LocalDate> dateList = getDateList(begin, end);

        //2.构造newUserList数据，新增用户列表
        List<Integer> newUserList = new ArrayList<>();

        //3.构造totalUserList数据，总用户列表
        List<Integer> totalUserList = new ArrayList<>();

        //循环遍历日期列表统计每日的新增用户数---user
        dateList.forEach(date -> {
            //select count(*) from user where create_time between '2025-10-31 00:00:00' and '2025-10-31 23:59:59.99999'
            Map map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); //'2025-10-31 00:00:00'
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); //'2025-10-31 23:59:59.99999'
            Integer newUser=userMapper.countByMap(map);
            newUserList.add(newUser);

            //统计总用户数
            //select count(*) from user where create_time < '2025-10-31 23:59:59.99999'
            map.put("beginTime",null);
            Integer totalUser=userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });

        //4.构造UserReportVO对象并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 统计指定日期范围内每天的订单数据，并生成订单统计报告。
     *
     * @param begin 统计的起始日期（包含）
     * @param end   统计的结束日期（包含）
     * @return 返回封装了订单统计数据的OrderReportVO对象，包括：
     *         - 日期列表
     *         - 每日总订单数列表
     *         - 每日有效订单数列表
     *         - 订单总数
     *         - 有效订单数
     *         - 订单完成率
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表数据 dateList
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        //循环遍历日期列表进行订单统计
        for (LocalDate date : dateList) {
            //2.获取每日总订单列表数 orderCountList
            //统计每日orders订单数量，条件：下单时间>=当前起始时间 and 下单时间<=当前结束时间
            Map map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); //'2025-10-31 00:00:00'
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); //'2025-10-31 23:59:59.99999'
            Integer orderCount = ordersMapper.countByMap(map);
            orderCountList.add(orderCount);

            //3.获取每日有效订单列表数 validOrderCountList
            //统计每日有效orders订单数量，条件：订单状态=已完成、下单时间>=当前起始时间 and 下单时间<=当前结束时间
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);

            //4.获取时间区间内的订单总数 totalOrderCount
            totalOrderCount += orderCount;

            //5.获取时间区间内的有效订单数 validOrderCount
            validOrderCount += validOrder;
        }

        //4.获取时间区间内的订单总数 totalOrderCount---写法二，使用stream流
//        totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();

        //6.获取订单完成率 orderCompletionRate
        Double orderCompletionRate=0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (validOrderCount+0.0) / totalOrderCount;
        }

        //7.构造OrderReportVO对象并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询指定时间范围内销量排名前10的商品统计信息
     * @param begin 统计开始日期
     * @param end 统计结束日期
     * @return SalesTop10ReportVO 销量前10商品报表数据对象，包含商品名称列表和对应销量列表
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.构造nameList，商品名称列表
        List<String> nameList = new ArrayList<>();

        //2.构造numberList，商品销量（份数）列表
        List<Integer> numberList = new ArrayList<>();

        //查询订单明细表order_detail+订单表orders，条件：订单状态-已完成，下单时间
        Map map=new HashMap<>();
        map.put("status",Orders.COMPLETED);
        map.put("beginTime",LocalDateTime.of(begin,LocalTime.MIN));
        map.put("endTime",LocalDateTime.of(end,LocalTime.MAX));
        List<GoodsSalesDTO> List = ordersMapper.sumTop10(map);

        for (GoodsSalesDTO dto : List) {
            nameList.add(dto.getName());
            numberList.add(dto.getNumber());
        }

        //3.封装SalesTop10ReportVO对象并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出业务数据到Excel文件并提供下载
     * <p>
     * 该方法会查询最近30天的营业数据，包括概览数据和每日明细数据，
     * 然后使用POI将数据填充到Excel模板中，并通过HTTP响应输出流将生成的Excel文件返回给客户端浏览器。
     *
     * @param response HTTP响应对象，用于向客户端输出Excel文件
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dataBegin = LocalDate.now().minusDays(30);
        LocalDate dataEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dataBegin, LocalTime.MIN), LocalDateTime.of(dataEnd, LocalTime.MAX));

        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try{
            //基于模板文件创建一个新的Excel文件，工作簿对象
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取工作表对象Sheet
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+dataBegin+"至"+dataEnd);

            //填充概览数据
            //获取第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dataBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获取某一行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定时间区间内的日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        //循环插入日期数据，开始日期 <= 结束日期
        while (!begin.isAfter(end)) {
            //注意停止循环的条件，避免死循环
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        log.info("dateList={}",dateList);
        return dateList;
    }
}
